/**
 * 
 */
package xyz.zhengtank.grpc.client;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.grpc.ManagedChannel;
import io.grpc.netty.NettyChannelBuilder;
import xyz.zhengtank.grpc.HelloProto.HelloReply;
import xyz.zhengtank.grpc.HelloProto.HelloRequest;
import xyz.zhengtank.grpc.HelloProtoServiceGrpc;

/**
 * @author tank
 * @since 2018-03-30
 * @category 
 * 
 */
public class HelloProtoClient {
	
	private static final Logger LOG = LoggerFactory.getLogger(HelloProtoClient.class);
	
	private final ManagedChannel channel;
	
	private final HelloProtoServiceGrpc.HelloProtoServiceBlockingStub blockingStub;
	/**
	 * 客户端构造器
	 * @param host
	 * @param port
	 */
	public HelloProtoClient(String host, int port) {
		this(NettyChannelBuilder.forAddress(host,port).usePlaintext().build());
	}
	
	/**
	 * 重载构造器
	 * @param channel
	 */
	HelloProtoClient(ManagedChannel channel) {
		this.channel = channel;
		blockingStub = HelloProtoServiceGrpc.newBlockingStub(channel);
	}
	
	/**
	 * 客户端在给定时间内(5s)后关闭
	 * @throws InterruptedException 
	 * 
	 */
	public void shutdown() throws InterruptedException {
		channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
	}
	
	/**
	 * 模拟向服务器通信逻辑处理
	 * @param name
	 */
	public void sayHello(String name) {
		LOG.info("Will try to say hello to " + name + " ...");
		HelloRequest request = HelloRequest.newBuilder().setName(name).build();
		HelloReply response = null;
		try {
			response = blockingStub.sayHello(request);
		} catch (Exception e) {
			if(LOG.isWarnEnabled()) {
				LOG.warn("RPC failed: {0}", e.getMessage());
				return;
			}
		}
		
		LOG.info("Greeting: " + response.getReply());
	}
	
	public static void main(String[] args) throws InterruptedException {
		HelloProtoClient client = new HelloProtoClient("localhost", 50051);
		try {
			String user = "world";
			client.sayHello(user);
		} finally {
			client.shutdown();
		}
		
	}

}
